﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Metro.Core;

namespace Pictures
{
    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    public partial class WidgetControl : UserControl
    {
        private readonly List<string> _pictures = new List<string>();
        private DispatcherTimer _timer;
        private Random r;

        public WidgetControl()
        {
            InitializeComponent();
        }

        public void Load()
        {
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMinutes(Widget.Instance.Sett.Interval);
            _timer.Tick += new EventHandler(TimerTick);
            _timer.Start();

            var picsPath = Widget.Instance.Sett.PicturesDir;
            if (picsPath.Contains("%HOME%"))
                picsPath = picsPath.Replace("%HOME%", E.Path);
            if (Directory.Exists(picsPath))
            {
                var pics = from x in Directory.GetFiles(picsPath, "*.*", SearchOption.AllDirectories)
                           where x.ToLower().EndsWith("jpg") || x.ToLower().EndsWith("png")
                           select x;
                foreach (var p in pics)
                {
                    _pictures.Add(p);
                }
                r = new Random(Environment.TickCount);
                if (_pictures.Count > 0)
                    Picture.Source = new BitmapImage(new Uri(_pictures[r.Next(0, _pictures.Count - 1)]));
            }

            Widget.Instance.SetBackground(Brushes.Transparent);
        }

        void TimerTick(object sender, EventArgs e)
        {
            if (_pictures.Count > 0)
            {
                PictureBg.Source = new BitmapImage(new Uri(_pictures[r.Next(0, _pictures.Count - 1)]));

                var s = (Storyboard) Resources["SwitchPictureAnim"];
                s.Begin();
            }
        }

        private void DoubleAnimationCompleted(object sender, EventArgs e)
        {
            Picture.Source = PictureBg.Source;
            PictureBg.Source = null;
        }
    }
}
